<template>
  <div class="product-detail">
    <!-- 顶部导航栏 -->
    <div class="nav-bar">
      <div class="back-icon" @click="$router.back()">
        <van-icon name="arrow-left" />
      </div>
      <div class="title">积分兑换</div>
      <div class="share-icon" @click="handleShare">
        <van-icon name="share" />
      </div>
    </div>

    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <!-- 商品信息区域 -->
      <div class="product-container" v-if="!loading">
        <!-- 商品图片 -->
        <div class="product-images">
          <van-swipe class="swipe-container" :autoplay="3000" indicator-color="#ff6b6b">
            <van-swipe-item v-for="(image, index) in productImages" :key="index">
              <img :src="image" :alt="productDetail.name">
            </van-swipe-item>
          </van-swipe>
        </div>

        <!-- 商品信息 -->
        <div class="product-info">
          <h2 class="product-name">{{ productDetail.name }}</h2>
          <div class="product-brief">
            <div class="points">
              <span class="points-number">{{ productDetail.points }}</span>
              <span class="points-unit">积分</span>
            </div>
            <div class="stock">库存: {{ productDetail.stock }}件</div>
          </div>
          <div class="product-code">商品编号：{{ productDetail._id }}</div>
        </div>

        <!-- 使用期限 -->
        <div class="usage-period">
          <div class="section-title">使用期限</div>
          <div class="period-time">
            {{ formatDate(productDetail.startTime) }} - {{ formatDate(productDetail.endTime) }}
          </div>
        </div>

        <!-- 兑换规则 -->
        <div class="exchange-rules">
          <div class="section-title">兑换规则</div>
          <div class="rules-list">
            <div class="rule-item" v-if="productDetail.description">
              <van-icon name="description" color="#ff6b6b" />
              {{ productDetail.description }}
            </div>
            <div class="rule-item" v-if="productDetail.deliveryRules">
              <van-icon name="logistics" color="#ff6b6b" />
              {{ productDetail.deliveryRules }}
            </div>
            <div class="rule-item">
              <van-icon name="points" color="#ff6b6b" />
              每人限兑{{ productDetail.limitPerUser || 1 }}件
            </div>
          </div>
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-else class="loading-container">
        <van-loading type="spinner" color="#ff6b6b" />
      </div>
    </van-pull-refresh>

    <!-- 底部兑换按钮 -->
    <div class="bottom-bar">
      <div class="user-points">
        <van-icon name="points" color="#ff6b6b" />
        剩余积分：{{ userPoints }}
      </div>
      <button 
        class="exchange-btn" 
        @click="handleExchange"
      >
        立即兑换
      </button>
    </div>

    <!-- 兑换确认弹窗 -->
    <van-popup
      v-model:show="showExchangeModal"
      round
      position="bottom"
      :style="{ padding: '16px' }"
    >
      <div class="exchange-modal">
        <!-- 商品信息 -->
        <div class="product-brief">
          <img :src="productDetail.image" :alt="productDetail.name">
          <div class="brief-info">
            <div class="brief-points">{{ productDetail.points }}积分</div>
            <div class="brief-name">{{ productDetail.name }}</div>
          </div>
          <van-icon name="cross" class="close-icon" @click="showExchangeModal = false" />
        </div>

        <!-- 兑换数量 -->
        <div class="quantity-section">
          <div class="section-label">兑换数量</div>
          <div class="quantity-control">
            <van-stepper
              v-model="quantity"
              min="1"
              :max="maxExchangeQuantity"
              theme="round"
              button-size="28px"
            />
            <div class="quantity-tip">
              <van-icon name="info-o" />
              当前可兑换{{ maxExchangeQuantity }}份
            </div>
          </div>
        </div>

        <!-- 订单信息 -->
        <div class="order-info">
          <div class="info-item">
            <span>兑换数量</span>
            <span>{{ quantity }}件</span>
          </div>
          <div class="info-item">
            <span>所需积分</span>
            <span class="points">{{ totalPoints }}积分</span>
          </div>
          <div class="info-item">
            <span>剩余积分</span>
            <span>{{ userPoints - totalPoints }}积分</span>
          </div>
        </div>

        <!-- 确认按钮 -->
        <van-button 
          block 
          type="primary" 
          class="confirm-btn" 
          @click="confirmExchange"
        >
          确认兑换
        </van-button>
      </div>
    </van-popup>

    <!-- 分享面板 -->
    <van-share-sheet
      v-model:show="showShare"
      title="分享给好友"
      :options="shareOptions"
      @select="onShareSelect"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showConfirmDialog, 
  showToast, 
  showSuccessToast,
  showFailToast,
  Cell,
  CellGroup,
  Icon,
  Radio,
  RadioGroup,
  Button,
  Popup,
  Loading,
  PullRefresh,
  ShareSheet,
  Stepper,
  Swipe,
  SwipeItem
} from 'vant'

import { areaList } from '@vant/area-data'
import { apiGetProductDetail } from '../api/product'
import { createOrder } from '../api/order'
import { formatDate } from '../utils/date'
import { apiGetUserInfo } from '../api/user'

// 注册 Vant 组件
const vantComponents = {
  [Cell.name]: Cell,
  [CellGroup.name]: CellGroup,
  [Icon.name]: Icon,
  [Radio.name]: Radio,
  [RadioGroup.name]: RadioGroup,
  [Button.name]: Button,
  [Popup.name]: Popup,
  [Loading.name]: Loading,
  [PullRefresh.name]: PullRefresh,
  [ShareSheet.name]: ShareSheet,
  [Stepper.name]: Stepper,
  [Swipe.name]: Swipe,
  [SwipeItem.name]: SwipeItem
}

const route = useRoute()
const router = useRouter()
const loading = ref(true)
const refreshing = ref(false)
const productDetail = ref({})
const showExchangeModal = ref(false)
const showShare = ref(false)
const quantity = ref(1)

// 用户积分（实际项目中从用户状态获取）
const userPoints = ref(1000)

//获取用户信息
const getUserinfo = async () => {
  try {
    const res = await apiGetUserInfo(localStorage.getItem('userId'))
    
    userPoints.value = res.points || 0
    
    console.log(res)
  } catch (error) {
    showFailToast('获取用户信息失败')
    console.error(error)
  }
}

// 商品图片列表
const productImages = computed(() => {
  if (!productDetail.value.image) return []
  return [productDetail.value.image]
})

// 计算总积分
const totalPoints = computed(() => {
  return productDetail.value.points * quantity.value
})

// 计算最大可兑换数量
const maxExchangeQuantity = computed(() => {
  if (!productDetail.value.points) return 0
  const maxByPoints = Math.floor(userPoints.value / productDetail.value.points)
  const maxByStock = productDetail.value.stock || 0
  const maxByLimit = productDetail.value.limitPerUser || 3
  return Math.min(maxByPoints, maxByStock, maxByLimit)
})

// 是否可以兑换
const canExchange = computed(() => {
  return productDetail.value.stock > 0 && 
         userPoints.value >= productDetail.value.points &&
         productDetail.value.status !== 'off'
})

// 分享选项
const shareOptions = [
  { name: '微信', icon: 'wechat' },
  { name: '朋友圈', icon: 'wechat-moments' },
  { name: '复制链接', icon: 'link' },
]

// 确认兑换
const confirmExchange = async () => {
  try {
    const orderData = {
      userId: localStorage.getItem('userId'),
      items: [{
        itemId: productDetail.value._id,
        quantity: quantity.value
      }],
      address: {
        receiver: '张三',
        phone: '13800138000',
        address: '北京市朝阳区某某街道1号楼'
      }
    }

    const res = await createOrder(orderData)
    console.log(res);
    
    if (res._id) {
      showSuccessToast('兑换成功')
      showExchangeModal.value = false
      router.push('/orders')
    } else {
      showFailToast(res.message || '兑换失败')
    }
  } catch (error) {
    showFailToast('兑换失败，请重试')
    console.error(error)
  }
}

// 获取商品详情
const getProductDetail = async () => {
  try {
    loading.value = true
    const productId = route.params.id
    const data = await apiGetProductDetail(productId)
    productDetail.value = data
  } catch (error) {
    showFailToast('获取商品详情失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 下拉刷新
const onRefresh = async () => {
  await getProductDetail()
  refreshing.value = false
}

// 点击兑换按钮
const handleExchange = () => {
  if (!canExchange.value) {
    if (productDetail.value.stock <= 0) {
      showToast('商品已售罄')
    } else if (userPoints.value < productDetail.value.points) {
      showToast('积分不足')
    }
    return
  }
  showExchangeModal.value = true
}

// 处理分享
const handleShare = () => {
  showShare.value = true
}

// 处理分享选择
const onShareSelect = (option) => {
  if (option.name === '复制链接') {
    // 复制商品链接
    const url = window.location.href
    navigator.clipboard.writeText(url)
    showSuccessToast('链接已复制')
  } else {
    showToast(`请在APP内使用${option.name}分享`)
  }
  showShare.value = false
}

onMounted(() => {
  getProductDetail()
  getUserinfo()
})
</script>

<style scoped>
.product-detail {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 60px;
}

.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 44px;
  background: linear-gradient(to right, #ff7f50, #ff6b6b);
  color: white;
  display: flex;
  align-items: center;
  padding: 0 16px;
  z-index: 100;
}

.back-icon, .share-icon {
  font-size: 20px;
  padding: 8px;
}

.title {
  flex: 1;
  text-align: center;
  font-size: 16px;
}

.product-container {
  padding-top: 44px;
}

.swipe-container {
  height: 300px;
}

.swipe-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-info {
  background: white;
  padding: 16px;
  margin-bottom: 8px;
}

.product-name {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.product-brief {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
}

.points-number {
  font-size: 24px;
  color: #ff6b6b;
  font-weight: bold;
}

.points-unit {
  font-size: 14px;
  color: #ff6b6b;
  margin-left: 4px;
}

.stock {
  font-size: 14px;
  color: #666;
}

.product-code {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}

.usage-period,
.exchange-rules {
  background: white;
  padding: 16px;
  margin-bottom: 8px;
}

.section-title {
  font-size: 16px;
  color: #333;
  margin-bottom: 12px;
  font-weight: bold;
}

.period-time {
  color: #666;
  font-size: 14px;
}

.rules-list {
  color: #666;
  font-size: 14px;
  line-height: 1.6;
}

.rule-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.rule-item .van-icon {
  margin-right: 8px;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 50px;
  background: white;
  display: flex;
  align-items: center;
  padding: 0 16px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.user-points {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  color: #666;
}

.exchange-btn {
  background: linear-gradient(to right, #ff7f50, #ff6b6b);
  color: white;
  border: none;
  padding: 8px 24px;
  border-radius: 20px;
  font-size: 14px;
}

.exchange-btn:disabled {
  background: #ccc;
}

.exchange-modal {
  padding-bottom: env(safe-area-inset-bottom);
}

.product-brief {
  display: flex;
  align-items: center;
  padding-bottom: 20px;
  border-bottom: 1px solid #f5f5f5;
  position: relative;
}

.product-brief img {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  margin-right: 12px;
}

.brief-info {
  flex: 1;
}

.brief-points {
  font-size: 18px;
  font-weight: bold;
  color: #ff6b6b;
  margin-bottom: 4px;
}

.brief-name {
  font-size: 14px;
  color: #333;
}

.close-icon {
  position: absolute;
  right: 0;
  top: 0;
  padding: 8px;
  font-size: 18px;
  color: #999;
}

.section-label {
  font-size: 14px;
  color: #333;
  margin: 16px 0 12px;
  font-weight: 500;
}

.quantity-control {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.quantity-tip {
  font-size: 12px;
  color: #999;
  display: flex;
  align-items: center;
}

.quantity-tip .van-icon {
  margin-right: 4px;
}

.order-info {
  margin-top: 20px;
  padding: 16px;
  background: #f8f8f8;
  border-radius: 8px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
}

.info-item:last-child {
  margin-bottom: 0;
}

.info-item .points {
  color: #ff6b6b;
  font-weight: 500;
}

.confirm-btn {
  margin-top: 24px;
  height: 44px;
  font-size: 16px;
  border: none;
  border-radius: 22px;
  background: linear-gradient(to right, #ff7f50, #ff6b6b);
}

.confirm-btn:disabled {
  opacity: 0.6;
  background: #ccc;
}
</style> 